package com.taobao.tbk.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taobao.tbk.utils.StringRedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class ItemProcService{

    @Autowired
    private StringRedisUtil stringRedisUtil;

    /**
     * 处理淘宝获取的json字符串
     * @param itemStr
     */
    @Async
    public void processItemStr(String itemStr) {
//        System.out.println("Thread Name:" + Thread.currentThread().getName());
        Object object = JSON.parseObject(itemStr);
        if (object == null) {
            return;
        }
        JSONObject jsonObject = (JSONObject) object;
        JSONArray materialJsonArr = this.getMaterialResList(jsonObject);
        if (materialJsonArr == null) {
            return;
        }
        for (int i = 0; i < materialJsonArr.size(); i++) {
            JSONObject itemJsonObject = materialJsonArr.getJSONObject(i);
            this.processItemJsonObject(itemJsonObject);
        }
    }

    /**
     * 获取物料列表
     * @param object
     * @return
     */
    private JSONArray getMaterialResList(JSONObject object) {
        JSONObject materialJsonObject = (JSONObject) object.get("tbk_dg_material_optional_response");
        if (materialJsonObject == null) {
            return null;
        }
        JSONObject materialResListJsonObj = (JSONObject) materialJsonObject.get("result_list");
        if (materialResListJsonObj == null) {
            return null;
        }
        return (JSONArray) materialResListJsonObj.get("map_data");
    }

    /**
     * 将物料缓存到redis
     * @param itemJsonObject
     */
    private void processItemJsonObject(JSONObject itemJsonObject) {
        String itemId = itemJsonObject.getString("num_iid");
        if (!stringRedisUtil.exists(itemId)) {
            stringRedisUtil.set(itemId, itemJsonObject.toJSONString());
        }
    }

}
